const http=require('http')
const mysql=require('mysql')
const fs=require('fs')
const path=require('path')
const _url=require('url')
const mime=require('mime')
const connection = mysql.createConnection({
    host:'localhost',
    user:'admin',
    password:'123456',
    database:'admin'
})

// 连接数据库
connection.connect()
console.log('数据库链接成功')

let sql='select * from list'
connection.query(sql,(err,res)=>{
    if(err){
        console.log(err.message)
        return
    }
   dataList=JSON.stringify(res)
   console.log(dataList)
   fs.writeFile('./json/list.json',dataList,err=>{
       if(err){
        console.log('json-文件写入失败')
           return
       }
   })
})
const server=http.createServer((req,res)=>{
    let route=_url.parse(req.url).pathname
    let extname=path.extname(route)
    let base=mime.getType(route)
    let lj='./html'
    res.statusCode==200
    res.setHeader('Content-Type','text/html;charset=utf-8')
    console.log(route)
    if(route=='/favicon.ico'){
         return
    }
    if(extname=='.css'){
        lj='./html/css'
    }
    if(extname=='.js'){
        lhj='./html/js'
    }
    res.writeHead(200,{"Content-Type":`${mime};charset=utf-8`})
    fs.readFile(lj+route,(err,data)=>{
        if(err){
            console.log(err.message)
            return
        }
        res.end(data)
    })
    console.log(base,extname)
})
server.listen(8070,'127.0.0.1',()=>{
    console.log(`服务器运行在：http://127.0.0.1:8070`)
})
// 关闭数据库链接
connection.end()
console.log('数据库链接结束')